package org.budo.dubbo.protocol.http.spring.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.dubbo.protocol.http.dispatcher.servlet.ServletProtocolRequest;
import org.budo.dubbo.protocol.http.dispatcher.servlet.ServletProtocolResponse;
import org.budo.dubbo.protocol.http.view.render.ViewRender;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import lombok.Getter;
import lombok.Setter;

/**
 * 可以在Spring MVC中使用dubbo.protocol.http.ViewRender来序列化异常对象
 * 
 * @author lmw
 */
@Getter
@Setter
public class ViewRenderToSpringMvcHandlerExceptionResolver implements HandlerExceptionResolver {
    private static final Logger log = Slf4j.getLogger();

    private ViewRender viewRender;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (null == this.getViewRender()) {
            return null;
        }

        try {
            this.getViewRender().renderView(new ServletProtocolRequest(request), new ServletProtocolResponse(response), ex);
        } catch (Throwable e) {
            log.error("#27 renderView error, e=" + e, e);
        }

        return null;
    }
}